package com.carcontrol.rotate.base;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.carcontrol.rotate.AppManager;
import com.carcontrol.rotate.LoadingDialog;
import com.carcontrol.rotate.util.UIHelper;
import com.carcontrol.rotate.utils.CRC16;
import com.easy.carpanel.uart.uartJnit;
import com.example.x6.serial.SerialPort;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public abstract class BaseFragment extends Fragment {
	protected LoadingDialog loadingDialog;
	protected Context context;

	public byte[] bytes = new byte[]{0x00,0x01,0x02,0x03,0x04,0x05};
	private SerialPort serialttyS1;
	public InputStream ttyS1InputStream;
	public OutputStream ttyS1OutputStream;

	public static int width = BaseApplication.width;
	public static int height = BaseApplication.height;
	public static float density = BaseApplication.density;

	public static int width0 = BaseApplication.width0;
	public static int height0 = BaseApplication.height0;

	public static int width_d = 246*width/width0;
	public static int height_d = 140*height/height0;

	public String headerData = "5aa5";
	public String cmdheader = "5AA50883";
	public static  int fd;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getContext();

//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//			width_d = 246*width/width0;
//			height_d = 140*height/height0;
//		}else{
//			width_d = 0;
//			height_d = 0;
//		}

//		fd =  uartJnit.getInstance().fd;

		IntentFilter filter = new IntentFilter("carcontrol.broadcast.action");
		context.registerReceiver(mReceiver, filter);

		Log.e("bf===onCreate", Build.VERSION.SDK_INT+"==="+ Build.VERSION_CODES.N+"==="+width_d+"==="+height_d+"==="+fd);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		loadingDialog = new LoadingDialog(getActivity());
//		loadingDialog.setMessageText("数据加载...");
//		imageManager = new ImageManager(getActivity());
//		autoHelper = new LibraryHelper(getActivity());

		context = getActivity();
		BaseApplication.context = context;

//		init_serial();	//TODO
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		Log.e("bf===onDestroy", Build.VERSION.SDK_INT+"==="+ Build.VERSION_CODES.N+"==="+width_d+"==="+height_d+"==="+fd);

		if(mReceiver!=null){
			context.unregisterReceiver(mReceiver);
		}
	}

	public void send(String cmd) {
		Log.e("send==", "===" + toCmd(cmd));

		uartJnit.getInstance().sendCmds(toCmd(cmd));
//		uartJnit.getInstance().sendCmds("5AA50883D2E0000000903A");	//5AA50883D1E0003000C03A

//		byte[] bs = hexStringToByte(cmd);
//
//		Log.e("send==", bs[0]+"===" + bs[1]);
//
////      byte[] bb = new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88};
//		byte[] bb = new byte[]{0x2E, (byte) 0x88, 0x0A, (byte)0x90, 0x00, (byte)bs[0], (byte)bs[1], 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88};
//		byte b = getCheckCanboxByte(bb);
//		Log.e("send===2", "===" + b);
//		sendData(new byte[]{0x2E, (byte)0x88, 0x0A, (byte)0x90, 0x00, (byte)bs[0], (byte)bs[1], 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, b});
	}

	private byte getCheckCanboxByte(byte[] buffer) {
		int lenght = buffer.length;
		byte check = 0;//buffer[1];
		for (int i =1; i < lenght; i++) {
			check += buffer[i];
		}

		Log.e("getCheckCanboxByte==", "===" + check);

//        return check;
		return (byte) (check ^ 0xff);
	}

	/**
	 * 数据发送到can线
	 * @param buffer  智慧派定义的数据结构形式
	 */
	public void sendData(byte[] buffer) {
		Log.e("sendData===", "===" + buffer);
		String data = byteArrayToHexString(buffer);
		Log.e("sendData===1", "Activity cmdcan ===send bytes:" + data);
		Intent intent = new Intent();
		intent.setAction("com.unibroad.candata.receive");
		intent.putExtra("cmd", data);
        context.sendBroadcast(intent);
//
//        //数据发送演示
//        strbuffer.append(">>>>发送：").append(data).append("\n");
//        data_tv.setText(strbuffer);
	}

	public void sendData(String data) {
//		String data = byteArrayToHexString(buffer);
		Log.e("sendData===", "Activity cmdcan ===send bytes:" + data);
		Intent intent = new Intent();
		intent.setAction("com.unibroad.candata.receive");
		intent.putExtra("cmd", data);
		context.sendBroadcast(intent);
//
//        //数据发送演示
//        strbuffer.append(">>>>发送：").append(data).append("\n");
//        data_tv.setText(strbuffer);
	}

	/**
	 * 字符串转Byte数组工具
	 * @param hex
	 * @return
	 */
	private static byte[] hexStringToByte(String hex) {

		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}

	private static int toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}
	/**
	 *  Byte数组转字符串工具
	 * @param byteArray
	 * @return
	 */
	private static String byteArrayToHexString(byte[] byteArray) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (byteArray == null || byteArray.length <= 0) {
			return null;
		}
		for (int i = 0; i < byteArray.length; i++) {
			int v = byteArray[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}



	protected abstract void doAction1(String myDevice, String myStatus);

//	protected abstract void doAction2(String arg);

	BroadcastReceiver mReceiver = new BroadcastReceiver() {
		private String action = null;

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();

			Log.e("f1===mReceiver", intent+"==="+action);

			if ("carcontrol.broadcast.action".equals(action)) {
				int count = intent.getIntExtra("count", 0);

				String myDevice = intent.getStringExtra("feedDevice");
				String myStatus = intent.getStringExtra("feedStatus");

				doAction1(myDevice, myStatus);

				Log.e("f1===mReceiver_1", myDevice+"==="+myStatus);



			}
		}
	};


	/* 打开串口 */
	private void init_serial() {
		try {
			serialttyS1 = new SerialPort(new File("/dev/ttyS1"),115200,0);
			ttyS1InputStream = serialttyS1.getInputStream();
			ttyS1OutputStream = serialttyS1.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void write(byte[] bytes){
		/* 串口发送字节 */
		try {
			ttyS1OutputStream.write(bytes);   //TODO
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void read(byte[] bytes){
		/* 串口发送字节 */
		try {
			int temp = ttyS1InputStream.read(bytes);   //TODO
//			tv_temp.setText(temp+"℃");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String toCmd(String cmd0){
		String allCmdx = cmdheader;
		String tmpTmp = cmd0 + "0030";
		allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
		StringBuffer allCmd = CRC16.crc16x(allCmdx);
		String cmd = allCmd.substring(0,22);

		Log.e("toCmd===1", cmd0+"==="+cmd);

		return cmd;
	}

	public static String toHex(byte[] buffer, int read_count) {
		StringBuffer sb = new StringBuffer(read_count * 2);
		for (int i = 0; i < read_count; i++) {
			sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 15, 16));
		}
		return sb.toString();
	}
	public static byte charToByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}
	public static byte[] hexStringToBytes(String hex) {
		while (hex.length() < 2)
			return null;
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (charToByte(achar[pos]) << 4 | charToByte(achar[pos + 1]));
		}
		return result;
	}

	public void onStartCommon(final String title) {
		m_myHandler.post(new Runnable() {
			@Override
			public void run() {
				if (loadingDialog != null && !loadingDialog.isShowing()) {
					loadingDialog.setTitle(title);
					loadingDialog.show();
				}
			}
		});

	}

	public void onFailureCommon(final String s) {
		m_myHandler.post(new Runnable() {
			@Override
			public void run() {
				if (loadingDialog != null && loadingDialog.isShowing()){
					loadingDialog.dismiss();
				}
				UIHelper.ToastError(context, s);
			}
		});

	}

	Handler m_myHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message mes) {
			switch (mes.what) {
				case 0:
					break;
				default:
					break;
			}
			return false;
		}
	});

	public void finishMine() {
		AppManager.getAppManager().finishActivity(getActivity());
	}
}
